<template>
  <div class="reset-password">
    <base-form
      ref="form"
      column="single"
      label-width="110px"
      :form-list="formList"
      :form-rules="formRules" />
    <div class="actions">
      <el-button type="primary" size="small" @click="submit" :loading="submitLoading">修改</el-button>
      <el-button type="default" size="small" @click="cancel" :disabled="submitLoading">取消</el-button>
    </div>
  </div>
</template>

<script>
import BaseForm from '@/components/BaseForm'
import { editPasswordApi } from '@/api/modules/admin'
export default {
  components: { BaseForm },
  data () {
    const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'))
        } else {
          if (this.$refs['form'].getFormData().passwordCheck !== '') {
            this.$refs['form'].validateField('passwordCheck')
          }
          callback()
        }
      }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.$refs['form'].getFormData().password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      formList: [
        { type: 'password', label: '修改登录密码', prop: 'password' },
        { type: 'password', label: '再次输入密码', prop: 'passwordCheck' }
      ],
      formRules: {
        password: [
          { required: true, message: '请输入密码', trigger: ['change', 'blur'] },
          { validator: validatePass, trigger: ['change', 'blur'] }
        ],
        passwordCheck: [
          { required: true, message: '请再次输入密码', trigger: ['change', 'blur'] },
          { validator: validatePass2, trigger: ['change', 'blur'] }
        ]
      },
      submitLoading: false,
    }
  },
  methods: {
    submit () {
      this.$refs['form'].validate(async valid => {
        if(valid) {
          try {
            this.submitLoading = true
            const params = {
              ...this.$refs['form'].getFormData()
            }
            await editPasswordApi(params)
            this.$message({ type: 'success', message: '密码修改成功,下次登录请使用新密码' })
            this.$emit('success')
          } catch (err) {
            console.error(err)
          }
          this.submitLoading = false
        }
      })
    },
    cancel () {
      this.$emit('close')
    }
  }
}
</script>

<style lang="less" scoped>
.reset-password {
  max-width: 400px;
  margin: 0 auto;
  .actions {
    margin-top: 16px;
    text-align: center;
    .el-button {
      margin: 0 24px;
    }
  }
}
</style>